<template>
  <el-cascader
    ref="elCascader"
    style="width:100%"
    v-model="value"
    placeholder="请选择活动区域"
    :props="props"
  ></el-cascader>
</template>

<script>
import { getArea, getCity, getProvince, getStreet } from "@/api/addr";
export default {
  name: "Addr",
  props: {
    addr: {
      type: String,
      default: ""
    }
  },

  watch: {
    value(newVal) {
      console.log(newVal.join(","));
      this.$emit("update:addr", newVal.join(","));
    }
  },

  data() {
    return {
      value: "",
      props: {
        value: "code",
        label: "name",
        children: "children",
        lazy: true,
        lazyLoad: this.lazyLoad
      },
      selectProvince: null,
      selectCity: null,
      selectArea: null,
      selectStreet: null
    };
  },

  created() {
    this.getProvince();
    this.init();
  },

  methods: {
    // 获取选中的数组
    getCheckedNodes() {
      return this.$refs.elCascader.getCheckedNodes();
    },

    // 初始化 回显
    init() {
      this.value = this.addr.split(",");
    },

    // 动态加载
    lazyLoad(node, resolve) {
      console.log("🚀 ~ file: index.vue ~ line 58 ~ lazyLoad ~ node", node);
      const { level, value } = node;
      if (level == 0) {
        this.getProvince().then(res => {
          resolve(res);
        });
      }

      if (level == 1) {
        this.getCity(value).then(res => {
          resolve(res);
        });
      }

      if (level == 2) {
        this.getArea(value).then(res => {
          resolve(res);
        });
      }

      if (level == 3) {
        this.getStreet(value).then(res => {
          const nodes = res.map(item => {
            const leaf = true;
            const data = {
              ...item,
              leaf
            };
            return data;
          });
          resolve(nodes);
        });
      }
    },

    // 获取省份信息
    async getProvince() {
      const res = await getProvince().catch(err => console.log(err));
      return res.items;
    },

    // 获取城市
    async getCity(value) {
      const code = value;
      const res = await getCity({ code }).catch(err => console.log(err));
      return res.items;
    },

    // 获取区县
    async getArea(value) {
      const code = value;
      const res = await getArea({ code }).catch(err => console.log(err));
      return res.items;
    },

    // 获取街道
    async getStreet(value) {
      const code = value;
      const res = await getStreet({ code }).catch(err => console.log(err));
      return res.items;
    }
  }
};
</script>

<style></style>
